package com.auok;


import Util.WebUtil;
import com.auok.Response.ApiResult;
import io.vertx.core.json.JsonObject;
import io.vertx.reactivex.core.AbstractVerticle;
import io.vertx.reactivex.core.http.HttpServer;
import io.vertx.reactivex.ext.asyncsql.PostgreSQLClient;
import io.vertx.reactivex.ext.web.Router;

public class ServerVerticle extends AbstractVerticle {


    @Override
    public void start() throws Exception {

        var postgreSQLClientConfig = new JsonObject();

        postgreSQLClientConfig.put("host", config().getString("pgsql.host", "127.0.0.1"));
        postgreSQLClientConfig.put("port", config().getInteger("pgsql.port", 5432));
        postgreSQLClientConfig.put("maxPoolSize", 1000);
        postgreSQLClientConfig.put("username", config().getString("pgsql.username", "postgres"));
        postgreSQLClientConfig.put("password", config().getString("pgsql.password", "123456"));
        postgreSQLClientConfig.put("database", config().getString("pgsql.database", "auok"));

        var postgreSQLClient = PostgreSQLClient.createShared(vertx, postgreSQLClientConfig);

        HttpServer server = vertx.createHttpServer();

        Router router = Router.router(vertx);

        router.get("/").handler(ctx -> {
            ctx.response().end("are you ok?");
        });

        router.route().path("/api/server/*").handler(rc -> {
            boolean checksign = WebUtil.VerifySign(rc);

            if (checksign) {
                rc.next();
            } else {
                WebUtil.responseJsonByModel(rc, new ApiResult(false,
                        "验证签名失败",
                        null));

            }
        });

        new WebSocketController(postgreSQLClient).Register(router);
        new MessageController(postgreSQLClient).Register(router);


        router.route().last().failureHandler(context -> {
            WebUtil.responseJsonByModel(context, new ApiResult(
                    false,
                    "服务端异常",
                    null));
        });


        server.requestHandler(router::accept).listen(config().getInteger("listen.port", 8080));
    }


}
